#include "remotewidget.h"
#include "ui_remotewidget.h"

#include <QImage>
#include <QFile>
#include <QTime>
extern "C" {
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavcodec/avcodec.h>
#include <libavutil/opt.h>
}

#define BUFF_SIZE 1024*1024

RemoteWidget::RemoteWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RemoteWidget)
{
    ui->setupUi(this);
//    tcp = new QTcpSocket(this);
//    connect(tcp, &QTcpSocket::readyRead, this, &RemoteWidget::readData);
//    readStatus = 0;//0 就绪,1 header, 2 body
//    readSize = 0;

//    int ret;
//    pkt = av_packet_alloc();
//    pkt->data=new uint8_t[BUFF_SIZE];
//    // 初始化解码器
//    const AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_H264);
//    if (!codec) {
//        qCritical()<<"找不到解码器";
//    }
//    c = avcodec_alloc_context3(codec);
//    if (!c) {
//        qCritical()<<"初始化解码器失败";
//    }
//    /* open it */
//    if (avcodec_open2(c, codec, nullptr) < 0) {
//        qCritical()<<"打开解码器失败";
//    }

//    parser = av_parser_init(codec->id);
//    if (!parser) {
//        qCritical()<<"parser not found";
//        exit(1);
//    }

//    frame = av_frame_alloc();
//    this->m_sws = sws_getContext(1920, 1080, AVPixelFormat::AV_PIX_FMT_YUV420P
//                       , 1920, 1080, AVPixelFormat::AV_PIX_FMT_RGBA
//                       , SWS_POINT, nullptr, nullptr, nullptr);

//    m_argbFrame = av_frame_alloc();
//    m_argbFrame->format = AVPixelFormat::AV_PIX_FMT_ARGB;
//    m_argbFrame->width = 1920;
//    m_argbFrame->height = 1080;
//    ret = av_frame_get_buffer(m_argbFrame, 0);
//    if(ret<0)
//    {
//        qCritical()<<"Could not allocate the video frame data";
//    }

}

RemoteWidget::~RemoteWidget()
{
    avcodec_free_context(&c);
    av_frame_free(&frame);
    av_packet_free(&pkt);
    sws_freeContext(m_sws);
    delete tcp;
    delete ui;

}

void RemoteWidget::on_connectPushButton_clicked()
{
    tcp->connectToHost(ui->ipLineEdit->text(), 8888);
}

void RemoteWidget::readData()
{
    while(tcp->bytesAvailable())
    {
        if(readStatus == 0)
        {
            readSize+=tcp->read(reinterpret_cast<char*>(&pkt->size+readSize), sizeof(pkt->size)-readSize);
            if(readSize == sizeof(pkt->size))
            {
                readSize = 0;
                readStatus = 1;
            }
            qDebug()<<"准备接收画面"<<pkt->size;
        }
        else if (readStatus == 1)
        {
            if(pkt->size > BUFF_SIZE)
            {
                qCritical()<<"数据流包大于解码流";
            }

            readSize+=tcp->read(reinterpret_cast<char*>(pkt->data+readSize), pkt->size-readSize);
            if(readSize == pkt->size)
            {

                readSize = 0;
                readStatus = 0;

                qDebug()<<"接收:"<<pkt->size<<"\t 在时间:"<<QTime::currentTime().toString("hh:mm:ss zzz");
                //TODO: 解码，显示画面
                showFrame();
            }
        }
    }
}

void RemoteWidget::showFrame()
{
    int ret;
    ret = avcodec_send_packet(c, pkt);
    if(ret<0)
    {
        qCritical()<<"Error sending a packet for decoding";
        return;
    }
    while(ret >=0)
    {
        ret = avcodec_receive_frame(c, frame);
        if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
            return;
        else if (ret < 0) {
            fprintf(stderr, "Error during decoding\n");
            qCritical()<<"Error during decoding";
        }
        //显示图片
        qDebug()<<QString("正在解码第%1帧").arg(frame->coded_picture_number);
        sws_scale(m_sws, frame->data, frame->linesize, 0, frame->height, m_argbFrame->data, m_argbFrame->linesize);
        QImage img(reinterpret_cast<unsigned char*>(m_argbFrame->data[0]),1920, 1080, QImage::Format_RGBA8888);
        ui->labelShow->setPixmap(QPixmap::fromImage(img));
    }
}
